package logic

import (
	"context"
	"time"

	"app-video/common/constant"
	"app-video/common/xerr"
	"app-video/models"
	"app-video/protos"
	"app-video/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddVideoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddVideoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddVideoLogic {
	return &AddVideoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// AddVideo 新增视频
func (l *AddVideoLogic) AddVideo(in *protos.AddVideoRequest) (*protos.Empty, error) {
	nowTime := time.Now().Unix()
	result, err := l.svcCtx.VideoModel.Insert(l.ctx, &models.Video{
		UserId:     in.UserId,
		Title:      in.Title,
		PlayUrl:    in.PlayUrl,
		CoverUrl:   in.CoverUrl,
		CreateTime: nowTime,
		UpdateTime: nowTime,
	})
	if err != nil {
		return nil, xerr.New(xerr.VideoCreateError)
	}

	videoID, err := result.LastInsertId()
	if err != nil {
		return nil, xerr.New(xerr.VideoCreateError)
	}

	_, _ = l.svcCtx.Redis.LpushCtx(l.ctx, constant.UserVideoKey, videoID)
	return &protos.Empty{}, nil
}
